<?php
require_once(__PHY_LIB.'/class/Item.class.php');
require_once(__PHY_LIB.'/class/uWork.class.php');
require_once(__PHY_LIB.'/class/uWorkSku.class.php');
require_once(__PHY_LIB.'/class/uWorkSize.class.php');

/* status意义：
 * canceled：取消订单
 * unpaid：未付款订单
 * prepaid：已付款到担保方
 * paid：已成功付款
 * making：生产中
 * qualified：已质检
 * shipping：发货中
 * recieved：已签收，待确认付款
 * closed：已确认完成订单
 * issued：发生纠纷的
 * hided：被用户隐藏的已完成订单
 */
class Order extends Item {
	/// definition and constructor ///
	function Order($id=0, $field="") {
		Query::Query();
		$this->cfgKeyField("id");
		$this->cfgAllField("id,sn,owner_type,owner_id,time_added,time_updated,coupon_id,coupon_title,coupon_price,coin_price,payment_id,payment_money,payment_method,payment_sn,ship_id,ship_method,ship_sn,ship_sign,ship_area_id,ship_address,ship_mobile,ship_phone,ship_email,ship_postcode,ship_price,package_method,package_price,remark,total_price,status");
		$this->cfgTable("fnnc_order");
		if ("" == $field || "*" == $field) {
			$this->cfgField($this->mAllField);
		}
		else {
			$this->cfgField($field);
		}
		if (0 < $id) {
			$this->cfgWhere($this->mKeyField . "=" . $id);
			$this->load();
		}
		else {
			$this->set($this->mKeyField, $id);
		}
	}
	function invalid() {
		return false;
	}

	function remove() {
		if (!(0 < $this->getID())) { return false; }
		$this->set('status', 'removed');
		return $this->update();
	}

/// 商品及库存操作 ///
	function addWork($nWorkID, $nSizeID=0, $nKuangID=0, $nQuantity=1) {
		if (!(0 < $this->getID())) { return false; }
		$nWorkID = (int)$nWorkID;
		$nSizeID = (int)$nSizeID;
		$nKuangID = (int)$nKuangID;
		$nQuantity = (int)$nQuantity;
		/// 扣锁库存 ///
		$oSku = new uWorkSku();
		$oSku->loadUnique(array('work_id' => $nWorkID, 'size_id' => $nSizeID, 'kuang_id' => $nKuangID));
		if (!(0 < $oSku->getID())) { return false; }
		$oSku->set('stock', max(0, $oSku->get('stock') - $nQuantity)); // 减少现库存
		$oSku->set('stock_locked', $oSku->get('stock_locked') + $nQuantity); // 增加锁库存
		$oSku->update();
		/// 订单总价增加 ///
		$fUnitPrice = 'dollor' == $_SESSION['MONEY'] ? $oSku->get('price_en') : $oSku->get('price');
		$this->set('total_price', $this->get('total_price') + $fUnitPrice*$nQuantity);
		/// 增加到订单内容 ///
		$sQ = "INSERT INTO fnnc_order_work SET"
			. " order_id='".$this->getID()."'"
			. ",work_id='".addslashes($nWorkID)."'"
			. ",size_id='".addslashes($nSizeID)."'"
			. ",kuang_id='".addslashes($nKuangID)."'"
			. ",quantity='".addslashes($nQuantity)."'"
			. " ON DUPLICATE KEY UPDATE"
			. " quantity=quantity+'".addslashes($nQuantity)."'";
		Query::loadQuery($sQ);
		return true;
	}
	// 订单付款后，减少锁库存
	function reduceStockLock() {
		$oList = new uWorkSkuList("fnnc_order_work ow INNER JOIN unit_work_sku ws"
			. " ON ws.work_id=ow.work_id AND ws.size_id=ow.size_id AND ws.kuang_id=ow.kuang_id");
		$oList->cfgField("ws.*,ow.quantity");
		$oList->cfgWhere("ow.order_id='".$this->getID()."'");
		$oList->load();
		while ($oSku = $oList->nextItem()) {
			$oSku->set('stock_locked', max(0, $oSku->get('stock_locked') - $oSku->get('quantity'))); // 减少锁库存
			$oSku->update();
//@ echo $oSku->mSql."<br />\n";
		}
	}
	// 订单取消后，释放锁库存，加回到现库存中
	function releaseStockLock() {
		$oList = new uWorkSkuList("fnnc_order_work ow INNER JOIN unit_work_sku ws"
			. " ON ws.work_id=ow.work_id AND ws.size_id=ow.size_id AND ws.kuang_id=ow.kuang_id");
		$oList->cfgField("ws.*,ow.quantity");
		$oList->cfgWhere("ow.order_id='".$this->getID()."'");
		$oList->load();
		while ($oSku = $oList->nextItem()) {
			$oSku->set('stock', max(0, $oSku->get('stock') + $oSku->get('quantity'))); // 增加现库存
			$oSku->set('stock_locked', max(0, $oSku->get('stock_locked') - $oSku->get('quantity'))); // 减少锁库存
			$oSku->update();
//@ echo $oSku->mSql."<br />\n";
		}
	}

	function calcSerialNumber() {
		return 'sn';
	}

/// 订单修改日志 ///
	function getChangelog($sAction=false) {
		if (!(0 < $this->getID())) { return false; }
		if ($sAction) {
			$oOne = new Item();
			$oOne->cfgTable("fnnc_order_changelog");
			$oOne->cfgWhere("order_id='".$this->getID()."' AND action='".addslashes($sAction)."'");
			$oOne->cfgOrder("id DESC");
			$oOne->load();
			return $oOne->getData();
		}
		else {
			$oList = new ItemList();
			$oList->cfgTable("fnnc_order_changelog");
			$oList->cfgWhere("order_id='".$this->getID()."'");
			$oList->cfgOrder("id DESC");
			$oList->load();
			return $oList->fetchArray();
		}
	}
	function addChangelog($sAction, $rParam, $sRemark=false) {
		if (!(0 < $this->getID())) { return false; }
		$oOne = new Item();
		$sQ = "INSERT INTO fnnc_order_changelog SET "
			. "order_id='".$this->getID()."',"
			. "action='".addslashes($sAction)."',"
			. "time_changed='".($rParam['time_changed'] ? $rParam['time_changed'] : date('Y-m-d H:i:s'))."',"
			. "param='".addslashes(serialize($rParam))."',"
			. "remark='".addslashes($sRemark)."'";
		return $oOne->loadQuery($sQ);
	}

} /// end class Order.

class OrderList extends ItemList {
	/// definition and constructor ///
	function OrderList($tablename=null) {
		ItemList::ItemList();
		$this->cfgClass("Order");
		$this->cfgKeyField("id");
		$this->cfgAllField("id,sn,owner_type,owner_id,time_added,time_updated,coupon_id,coupon_title,coupon_price,coin_price,payment_id,payment_money,payment_method,payment_sn,ship_id,ship_method,ship_sn,ship_sign,ship_area_id,ship_address,ship_mobile,ship_phone,ship_email,ship_postcode,ship_price,package_method,package_price,remark,total_price,status");
		$this->cfgTable(null == $tablename ? "fnnc_order" : $tablename);
	}

} /// end class OrderList.
?>
